package com.example;

import org.eclipse.paho.client.mqttv3.*;

public class ChatClient {
    private final String broker = "tcp://localhost:1883"; // MQTT Broker地址
    private final String clientId;
    private MqttClient client;

    // 构造函数，传入用户名作为客户端ID
    public ChatClient(String username) throws MqttException {
        this.clientId = "JavaChatClient_" + username;
        client = new MqttClient(broker, clientId);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false); // 设置持久会话
        client.connect(options);
        client.subscribe("chat/topic");
    }

    // 发送消息，消息中包含发送者的用户名
    public void sendMessage(String username,String message) throws MqttException {
        String fullMessage = username + ": " + message;
        MqttMessage mqttMessage = new MqttMessage(fullMessage.getBytes());
        mqttMessage.setQos(2); // QoS等级
        client.publish("chat/topic", mqttMessage);
    }

    public void callback(MqttCallback callback) {
        client.setCallback(callback); // 设置回调
    }

    public void subscribe(String topic) throws MqttException {
        client.subscribe(topic); // 只订阅主题，不处理消息
    }
    // 处理接收到的消息
     /* public void subscribe(String topic) throws MqttException {
        client.subscribe(topic, (t, msg) -> {
            System.out.println("Received message: " + new String(msg.getPayload()));
        });
    }*/

    public void disconnect() throws MqttException {
        client.disconnect();
    }
}